package org.zheng.shop.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.zheng.shop.dto.ProductDTO;
import org.zheng.shop.entity.Category;
import org.zheng.shop.entity.Product;
import org.zheng.shop.repository.CategoryRepository;
import org.zheng.shop.repository.ProductRepository;
import org.zheng.shop.service.FileStorageService;
import org.zheng.shop.service.ProductService;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private CategoryRepository categoryRepository;
    
    @Autowired
    private FileStorageService fileStorageService;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public List<ProductDTO> getAllProducts() {
        List<Product> products = productRepository.findAllByOrderByPriorityDesc();
        return products.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductDTO> getProductsByCategory(Integer categoryId) {
        List<Product> products = productRepository.findByCategoryIdOrderByPriorityDesc(categoryId);
        return products.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductDTO> getLatestProducts(Integer limit) {
        List<Product> products = productRepository.findLatestProducts(limit);
        return products.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public ProductDTO getProductById(Integer id) {
        Product product = productRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("产品不存在"));
        return convertToDTO(product);
    }

    @Override
    @Transactional
    public ProductDTO createProduct(ProductDTO productDTO) {
        Category category = categoryRepository.findById(productDTO.getCategoryId())
                .orElseThrow(() -> new RuntimeException("类别不存在"));

        Product product = new Product();
        product.setName(productDTO.getName());
        product.setDescription(productDTO.getDescription());
        product.setPrice(productDTO.getPrice());
        product.setPriority(productDTO.getPriority());
        product.setImage(productDTO.getImage());
        product.setImages(productDTO.getImages());
        product.setCategory(category);
        product.setCategoryId(category.getId());
        product.setCreateTime(System.currentTimeMillis());

        Product savedProduct = productRepository.save(product);
        return convertToDTO(savedProduct);
    }

    @Override
    @Transactional
    public ProductDTO updateProduct(Integer id, ProductDTO productDTO) {
        Product product = productRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("产品不存在"));

        // 只有当传入了类别ID且与当前类别不同时才更新类别
        if (productDTO.getCategoryId() != null && !productDTO.getCategoryId().equals(product.getCategoryId())) {
            Category newCategory = categoryRepository.findById(productDTO.getCategoryId())
                    .orElseThrow(() -> new RuntimeException("类别不存在"));
            product.setCategory(newCategory);
            product.setCategoryId(newCategory.getId());
        }

        // 只更新传入的非空字段
        if (productDTO.getName() != null) {
            product.setName(productDTO.getName());
        }
        
        if (productDTO.getDescription() != null) {
            product.setDescription(productDTO.getDescription());
        }
        
        if (productDTO.getPrice() != null) {
            product.setPrice(productDTO.getPrice());
        }
        
        if (productDTO.getPriority() != null) {
            product.setPriority(productDTO.getPriority());
        }
        
        if (productDTO.getImage() != null) {
            product.setImage(productDTO.getImage());
        }
        
        if (productDTO.getImages() != null) {
            product.setImages(productDTO.getImages());
        }

        Product updatedProduct = productRepository.save(product);
        return convertToDTO(updatedProduct);
    }

    @Override
    @Transactional
    public void deleteProduct(Integer id) {
        if (!productRepository.existsById(id)) {
            throw new RuntimeException("产品不存在");
        }
        productRepository.deleteById(id);
    }

    @Override
    public String uploadProductImage(MultipartFile file) {
        return fileStorageService.storeFile(file);
    }

    private ProductDTO convertToDTO(Product product) {
        ProductDTO dto = new ProductDTO();
        dto.setId(product.getId());
        dto.setName(product.getName());
        dto.setDescription(product.getDescription());
        dto.setPrice(product.getPrice());
        dto.setPriority(product.getPriority());
        dto.setImage(product.getImage());
        dto.setImages(product.getImages());
        
        // 处理多图片
        if (product.getImages() != null && !product.getImages().isEmpty()) {
            dto.setImageList(List.of(product.getImages().split(",")));
        }
        
        dto.setCategoryId(product.getCategoryId());
        if (product.getCategory() != null) {
            dto.setCategoryName(product.getCategory().getName());
        }
        dto.setCreateTime(product.getCreateTime());
        return dto;
    }
} 